package pageShare

import (
	"context"
	"encoding/json"
	"errors"

	"laundry-service/app/client/internal/svc"
	"laundry-service/app/client/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePageShareLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdatePageShareLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePageShareLogic {
	return &UpdatePageShareLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdatePageShareLogic) UpdatePageShare(req *types.UpdatePageShareRequest) (resp *types.CreatePageShareReply, err error) {
	userId, _ := l.ctx.Value("userId").(json.Number).Int64()
	_, err = l.svcCtx.Db.GetAdminById(int(userId))
	if err != nil {
		return nil, err
	}

	pageShare, err := l.svcCtx.Db.GetPageShareById(req.Id)
	if err != nil {
		return nil, err
	}

	if req.Path != "" {
		_, err = l.svcCtx.Db.GetPageShareByPath(req.Path)
		if err == nil {
			return nil, errors.New("path already exists")
		}
		pageShare.Path = req.Path
	}
	if req.Title != "" {
		pageShare.Title = req.Title
	}
	if req.Description != "" {
		pageShare.Description = req.Description
	}
	if req.ImageUrl != "" {
		pageShare.ImageUrl = req.ImageUrl
	}

	err = l.svcCtx.Db.UpdatePageShare(pageShare)
	if err != nil {
		return nil, err
	}

	return &types.CreatePageShareReply{
		Id:          pageShare.ID,
		CreatedAt:   pageShare.CreatedAt.Format("2006-01-02 15:04:05"),
		UpdatedAt:   pageShare.UpdatedAt.Format("2006-01-02 15:04:05"),
		Path:        pageShare.Path,
		Title:       pageShare.Title,
		Description: pageShare.Description,
		ImageUrl:    pageShare.ImageUrl,
	}, nil
}
